import os


def listFile(path):
    """
    列出文件夹中的文件名，并排序
    :param path: 文件夹路径
    :return: 文件列表
    """
    if os.path.exists(path):
        files = os.listdir(path)
        files.sort()
        return files
    else:
        print("input file error")
        exit(0)


def getRun(paragraphs, pattern):
    """
    获取docx中的run
    :param paragraphs: docx中的paragraphs
    :param pattern: 匹配字符串
    :return: 包含字符串所属的run
    """
    for paragraph in paragraphs:
        for run in paragraph.runs:
            if pattern in run.text:
                return run
    return None


def tryWrite2Excel(sheet, loc, dict, key, valueLoc=0):
    """
    用于excel文件写入，报错是抛出异常
    :param sheet: excel工作表
    :param loc: 表中写入的坐标
    :param dict: 填入underlineDic 或 textDic
    :param key: 字典的key
    :param valueLoc: value如果是list的下标
    """
    try:
        if isinstance(dict[key], list):
            sheet[loc] = dict[key][valueLoc]
        else:
            sheet[loc] = dict[key]
    except Exception as e:
        print(f"[“{key}”]无法写入, 请手工检测并填写。 {e}".format(key=key, e=e))


